/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.sstech.member.core.util;

import java.util.Date;

public class SequenceUtils {

	private static int seq_file = 0;
	private static int max_file = 99999;
	
	/**
	 * 生成随机数字的流水号
	 * 
	 * @param size
	 * @return
	 */
	public synchronized static String generateRandomSerialNum(int size) {

		int x = 0;
		do {
			x = RandomUtils.genRandom(10);
		} while (x <= 0);

		return x + RandomUtils.generateInteger(size - 1);
	}
	
	/**
	 * 生成订单/交易流水号
	 * @return
	 */
	public synchronized static String generateOrderSerialNum() {
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
		}
		
		String ser = DateUtils.format(new Date(), DateUtils.fullFormat1) + RandomUtils.generateInteger(2);
		
		return ser;
    }
	
	/**
	 * 生成通用流水号
	 * @return
	 */
	public synchronized static String generateDefaultSerialNum() {
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
		}
		
		String ser = System.currentTimeMillis() + RandomUtils.generateInteger(4);
		
		return ser;
    }
	
	public static String generatorFileSerialNumber() throws Exception {
		
		String nowseq = int2Str(seq_file, 5);
		seq_file = setNextSeq(seq_file, max_file);
		
		return "FILE" + System.currentTimeMillis() + nowseq + RandomUtils.genRandomUpperAlphaAndDec(5);
	}
	
	private static String int2Str(int num, int length) {
		String str = String.valueOf(num);
		while (str.length() < length) {
			str = "0" + str;
		}
		
		return str;
	}
	
	private static int setNextSeq(int nowSeq, int max) {
		if (nowSeq >= max) {
			return 0;
		} else {
			return ++nowSeq;
		}
	}

}
